package com.vercon.otamirror.utils.helper;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.vercon.commonmirror.Constants;
import com.vercon.commonmirror.base.BaseEvent;
import com.vercon.commonmirror.utils.LogUtils;
import com.vercon.otamirror.R;
import com.vercon.otamirror.dialog.FirmwareUpdateDialog;
import com.vercon.otamirror.dialog.UpdateFirmwareDialog;
import com.vercon.otamirror.event.MoreAppEvent;
import com.vercon.otamirror.fragment.HomeFragment;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by csh on 2021/5/17
 */
public class FragmentOpenManager {

    /**
     * Fragment 管理器
     */
    private FragmentManager fManager;

    /**
     * 装Fragment的容器
     */
    private int layoutId;

    /**
     * 该Activity所有fragment的集合
     */
    private final List<Fragment> fragments;

    private static FragmentOpenManager fragmentOpenManager;
    private static final String tag = FragmentOpenManager.class.getSimpleName();

    public static FragmentOpenManager getInstance() {
        if (fragmentOpenManager == null) {
            synchronized (FragmentOpenManager.class) {
                if (fragmentOpenManager == null) {
                    fragmentOpenManager = new FragmentOpenManager();
                }
            }
        }
        return fragmentOpenManager;
    }

    /**
     * FragmentActivity 实例
     */
    public FragmentOpenManager() {
        fragments = new ArrayList<>();
    }

    /**
     * 设置容器的Id
     *
     * @param layoutId
     */
    public void setLayoutId(int layoutId) {
        this.layoutId = layoutId;
    }

    /**
     * @param fragment 要替换的 fragment
     * @param fragment 标签
     * @param
     */
    public void switchFragment(Fragment fragment, FragmentActivity activity) {
        try {
            if (!isNoTop(fragment)) {
                LogUtils.d("隐藏虚拟键");
//            MainApplication.getContext().setVirtualKey(false);
                fragments.clear();
                fManager = activity.getSupportFragmentManager();
                fragments.add(fragment);
                FragmentTransaction fTransaction = fManager.beginTransaction();
                if(fragment.getClass().getSimpleName().equals(HomeFragment.class.getSimpleName())){
                    fTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                            .replace(layoutId, fragment, fragment.getClass().getSimpleName())
                            .commitAllowingStateLoss();
                    fragment.setMenuVisibility(true);
                }else {
                    fragment.setMenuVisibility(true);
                    fTransaction.replace(layoutId, fragment, fragment.getClass()
                                    .getSimpleName())
                            .setCustomAnimations(R.anim.in_home_weather_fragment, 0)
                            .commitAllowingStateLoss();
                }
                isVirtualVisible_two();
                LogUtils.i(tag, "switchFragment " + fragments.size() + "  " + fragment.getClass().getSimpleName() + "  " + fManager.getFragments().size());
            } else {
                LogUtils.e(tag, "Fragment is on top");
            }
        }catch (Exception e){}

    }

    /**
     * @param fragment 要替换的 fragment
     * @ fragment 标签
     */
    public void addFragment(Fragment fragment, FragmentActivity activity) {
        try {
            if (!isNoTop(fragment)) {
                fManager = activity.getSupportFragmentManager();
                FragmentTransaction fTransaction = fManager.beginTransaction();

                for (Fragment fragment1 : fragments) {
                    if (fragment1.getClass().getSimpleName().equals(fragment.getClass().getSimpleName())) {
                        fTransaction.remove(fragment);
                        fragments.remove(fragment1);
                        break;
                    }
                }
                if (fragments.size() != 0) {
                    fragments.get(fragments.size() - 1).setMenuVisibility(false);//回调最后一个fragment的状态
                }
                fragment.setMenuVisibility(true);
                fragments.add(fragment);
                fTransaction.setCustomAnimations(R.anim.in_home_weather_fragment, 0)
                        .add(layoutId, fragment, fragment.getClass().getSimpleName())
                        .commitAllowingStateLoss();
                isVirtualVisible_two();
                for (int i = 0; i < fragments.size(); i++) {
                    if(fragments.size() > 2 && fragments.get(i).getClass().getSimpleName().equals(HomeFragment.class.getSimpleName())){
                        fragments.get(i).setMenuVisibility(false);
                    }
                }
                LogUtils.i(tag, "addFragment " + fragments.size() + "  " + fragment.getClass().getSimpleName() + "  " + fManager.getFragments().size());
            } else {
                LogUtils.e(tag, "Fragment is on top");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //防止顶部相同的，且不是HomeFragment 的 fragment添加
    private boolean isNoTop(Fragment fragment) {
        if (fragments.size() != 0 && !fragment.getClass().getSimpleName().equals(HomeFragment.class.getSimpleName())) {
            return fragments.get(fragments.size() - 1).getClass().getSimpleName().equals(fragment.getClass().getSimpleName());
        }
        return false;
    }

    public String getTopFragmentName() {
        synchronized (fragments) {
            if (fragments.size() != 0) {
                return fragments.get(fragments.size() - 1).getClass().getSimpleName();
            }
        }
        return "";
    }

    /**
     * 模拟按下返回键
     *
     * @ 返回到的Fragment的名字
     * @ 模式
     * FragmentManager.POP_BACK_STACK_INCLUSIVE
     * if name is null,flags is zero
     */
    public void onBack(FragmentActivity activity) {
        try {
            if (fragments.size() > 0) {

                if (fragments.size() == 1 && fragments.get(0).getClass().getSimpleName().equals(HomeFragment.class.getSimpleName())) {
                    fManager = activity.getSupportFragmentManager();
                    if (fManager.getFragments().size() > 1) {
                        FragmentTransaction fragmentTransaction = fManager.beginTransaction();
                        List<Fragment> fragments = fManager.getFragments();
                        for (Fragment fragment : fragments) {
                            if (!fragment.getClass().getSimpleName().equals(HomeFragment.class.getSimpleName())) {
                                fragmentTransaction.remove(fragment);
                            }
                        }
                        fragmentTransaction.commitAllowingStateLoss();
                    }
                    return;
                }
                fManager = activity.getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fManager.beginTransaction();
                fragmentTransaction.remove(fragments.get(fragments.size() - 1)).commitAllowingStateLoss();
                fragments.remove(fragments.get(fragments.size() - 1));
                isVirtualVisible_two();
                if (fragments.size() != 0) {
                    fragments.get(fragments.size() - 1).setMenuVisibility(true);//回调最后一个fragment的状态
                    LogUtils.i(tag, "onBack last" +  fragments.get(fragments.size() - 1).getClass().getSimpleName());
                }
                LogUtils.i(tag, "onBack " + fragments.size() + "  " + "  " + fManager.getFragments().size());

                if (fManager.getFragments().size() == 0 || fragments.size() == 0) {
                    fragments.clear();
                    switchFragment(new HomeFragment(), activity);
                }
                boolean appstoreisHidden = false;

                for (int i = 0; i < fragments.size(); i++) {
                    if(fragments.size() == 2 && appstoreisHidden && fragments.get(i).getClass().getSimpleName().equals(HomeFragment.class.getSimpleName())){
                        fragments.get(i).setMenuVisibility(true);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }



    /**
     * 通过tag获取到某个Fragment
     *
     * @param
     * @return
     */
    public Fragment getFragment(String className) {

        for (Fragment fragment : fragments) {
            if (fragment.getClass().getSimpleName().equals(className)) {
                return fragment;
            }
        }
        return null;
    }




    /**
     * 2次执行去掉虚拟键
     */
    private void isVirtualVisible_two(){
        isVirtualVisible();
    }

    /**
     * 设置虚拟键是否需要显示
     */
    private void isVirtualVisible() {
        try {
            if (fragments != null && fragments.size() > 0) {
                if (fragments.size() == 1) {
                    EventBus.getDefault().post(new MoreAppEvent(MoreAppEvent.IS_NO_SHOW));
                } else {
                        if (fragments.get(fragments.size() - 1).getClass().getSimpleName().equals(FirmwareUpdateDialog.class.getSimpleName())
                                || fragments.get(fragments.size() - 1).getClass().getSimpleName().equals(UpdateFirmwareDialog.class.getSimpleName())

                        ){
                            EventBus.getDefault().post(new MoreAppEvent(MoreAppEvent.IS_NO_SHOW));
                            LogUtils.d("MoreAppEvent.IS_NO_SHOW");
                        } else {
                            EventBus.getDefault().post(new MoreAppEvent(MoreAppEvent.IS_SHOW));
                            LogUtils.d("MoreAppEvent.IS_SHOW");
                        }
                    }

            }
        }catch (Exception e){

        }

    }









    /**
     * 获取所有的Fragment
     *
     * @return
     */
    public List<Fragment> getFragmentList() {
        return fragments;
    }

    /**
     * 获取Fragment管理器
     *
     * @return
     */
    public FragmentManager getFragmentManager() {
        return fManager;
    }

    public void onDestroy() {
        fragments.clear();
        fragmentOpenManager = null;
    }
} 